<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>成语接龙版本3</title>
<style type="text/css">
h1{ color: red;}
.kuang{ padding: 20px;}
.content{ border: 1px solid gray; border-radius: 20px; margin-bottom: 10px; padding: 20px;}
input,button { border-radius: 6px; outline: none; padding: 6px;}
.msg{ color: red; font-weight:bold; margin-bottom: 10px}
.history>p:nth-child(even){ color: red; font-weight: bold;}
</style>
</head>
<body>
<div class='kuang'>
	<div class='content'>
		<h1>人机大战之成语接龙</h1>
		<div class='history'></div>
	</div>
	<div class='msg'></div>
	<input name='chengyu' onkeypress="keypress()"/>
	<button onclick='check()'>接龙</button>
	<button onclick='again()'>再来一局</button>
</div>
<script type="text/javascript">
let first=''
let count=0
let $=function(selector){
	return document.querySelector(selector)
}
let $$=function(selector){
	let nl=document.querySelectorAll(selector) //NodeList
	return Array.prototype.slice.call(nl) //转换为数组
}
function keypress(){
	console.log(event)
	if(event.charCode==13){//是回车键
		$('button').click()//模拟提交按钮的单击事件
	}
}
function again(){
	post({op:'begin'})
	first=''
	$('input').value=$('.msg').innerText=''
	$$('.history p').forEach(p=>{
		p.remove()
	})
	$('input').focus()
}
async function check(){
	let msg=null
	let cy=$('input[name="chengyu"]').value.trim()
	if(cy.startsWith(first)){ //用户输入的成语是以first开头吗？
		if(cy.length>=3 && cy.length<=14){
			let r=await post({op:'check', cy})
			console.log(999,r)
			if(r.ok){
				let history=$('.history')
				let pp = document.createElement('p')
				pp.innerText= ++count+'. [人] '+cy
				history.append(pp)
				if(r.cy){//计算机接龙成功
					first=r.first
					let pj = document.createElement('p')
					pj.innerText= ++count+'. [机] '+r.cy
					history.append(pj)
					$('.msg').innerText=''
					
				}else{
					$('.msg').innerText='恭喜你战胜了计算机~'
					$('input').disabled=true
					$('button').disabled=true
				}
			}else{
				$('.msg').innerText=r.msg
			}
			$('input').value=''
			$('input').focus()
			return
		}
		msg="请正确输入成语，输入的成语应该在3到14个汉字之内~"
	}else{
		msg="Sorry，违反接龙规则，请输入以“"+first+"”字开头的成语~"	
	}
	$('.msg').innerText=msg //显示错误信息
	$('input').value=''
	$('input').focus()
}
async function post(obj){
	try{
		let url='http://localhost:8080/chengyu/api'
		let data={
			method: 'post',
			body: JSON.stringify(obj),
			headers: { 'Content-Type':'application/json' }
		}
		let response = await fetch(url,data)
		let json = await response.json()
		return json
	}catch(e){
		console.log('Error: ', e)
	}
	return null
}
</script>
</body>
</html>